using DevExpress.Web.ASPxTreeView;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web.UI;
using EntryExit.Utils;

namespace EntryExit
{
    public partial class MainMaster : BaseMaster
    {
        public event TreeViewNodeEventHandler MasterTreeViewNodeSelected;

        public event EventHandler ClickEventHandler;
        List<Employee> lstEmployee = new List<Employee>();
        public bool showSearch = true;
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {

                if (!IsPostBack)
                {
                    // Resource  : Rajkumar.GS
                    // Date      : 13-Feb-2014
                    // Purpose   : On click 'Search' button without entering any text in employee dropdown control, it was crashing.
                    // btnSearch.Attributes.Add("onclick", "javascript:return validateSearch();");


                    FillSubOrdinatesTreeView();
                    ASPxMenu2.Items[12].Visible = false;
                    if (IsAdmin)
                    {
                        ASPxMenu2.Items[10].Visible = true;
                        ASPxMenu2.Items[11].Visible = true;
                        ASPxMenu2.Items[0].Visible = true;
                        ASPxMenu2.Items[6].Visible = true;
                        ASPxMenu2.Items[7].Visible = true;
                        ASPxMenu2.Items[12].Visible = true;
                        if (EmployeeTreeData.SubEmployees.Count > 0 && showSearch)
                        {
                            divSearch.Visible = true;

                            //cmbUser.DataSource = ConstructEmployeeList(EmployeeTreeData.SubEmployees);
                            //cmbUser.DataBind();
                        }



                    }
                    if (IsSupervisor)
                    {
                        divSearch.Visible = true;
                        ASPxMenu2.Items[0].Visible = true;

                    }
                    if (CurrentEmployee.IsCounselor)
                    {
                        ASPxMenu2.Items[6].Visible = true;
                    }

                }



                //else
                //{
                //    RestoreTreeSelection();
                //}
            }
            catch (Exception ex)
            {
                Logger.Error("Page : Main.master.cs, Event : Page_Load  Comment : Treeview Control Bind Error", ex);
                ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('An internal error occured. Reload the tool and try again. If issue still persists, please report to your administrator..!');", true);
            }
        }

        public void HideSearch()
        {
            showSearch = false;
            
        }

        protected void ASPxComboBox_OnItemsRequestedByFilterCondition_SQL(object source, DevExpress.Web.ASPxEditors.ListEditItemsRequestedByFilterConditionEventArgs e)
        {
            string filter = e.Filter;

            if (string.IsNullOrEmpty(filter)) return;
            List<Employee> lstEmployee = ConstructEmployeeList(EmployeeTreeData.SubEmployees).Where(em =>em.EmployeeName.ToLower().Contains(filter.ToLower()) || em.LPN.Contains(filter)).ToList();
            cmbUser.DataSource = lstEmployee;
            cmbUser.DataBind();
        }

        protected void ASPxComboBox_OnItemRequestedByValue_SQL(object source, DevExpress.Web.ASPxEditors.ListEditItemRequestedByValueEventArgs e)
        {
            //if (null == e.Value) return;

            //List<Employee> lstEmployee = ConstructEmployeeList(EmployeeTreeData.SubEmployees).Where(em => em.LPN == Convert.ToString(e.Value)).ToList();
            //cmbUser.DataSource = lstEmployee;
            //cmbUser.DataBind();
        }

        private List<Employee> ConstructEmployeeList(List<EmployeeTree> lstEmpTree)
        {
            

            foreach (var emp in lstEmpTree)
            {
                lstEmployee.Add(emp.Employee);
                foreach (var childEmp in emp.SubEmployees)
                {
                    lstEmployee.Add(childEmp.Employee);

                    if (childEmp.SubEmployees.Count > 0)
                    {
                        ConstructEmployeeList(childEmp.SubEmployees);
                    }
                }
            }

            return lstEmployee;
        }

        private void ExpandSelectedNode()
        {
            if (Session["selNode"] != null)
            {

                List<TreeViewNode> ParentList = (List<TreeViewNode>)Session["ParentList"];
                foreach (var item in ParentList)
                {
                    TreeViewNode tn = (TreeViewNode)(ParentList[ParentList.Count - ParentList.IndexOf(item) - 1]);
                    try
                    {
                        if (subOrdinatesTreeView.Nodes.FindByName(tn.Name) != null)
                        {
                            subOrdinatesTreeView.Nodes.FindByName(tn.Name).Expanded = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        if (tn == null)
                        {
                            Logger.Error("Page : Main.master.cs, Event : ExpandSelectedNode() :TreeViewNode tn object is null", ex);
                            throw ex;
                        }
                        Logger.Error("Page : Main.master.cs, Event : ExpandSelectedNode() :TreeViewNode tn name=" + tn.Name, ex);
                        throw ex;
                    }

                }
                TreeViewNode node = (TreeViewNode)Session["selNode"];
                node = subOrdinatesTreeView.Nodes.FindByName(node.Name);
                subOrdinatesTreeView.ExpandToNode(node);
                subOrdinatesTreeView.SelectedNode = node;
            }
        }    

        private void FillSubOrdinatesTreeView()
        {
            EmployeeTree treeData = EmployeeTreeData;
            TreeViewNode resultingNode = subOrdinatesTreeView.Nodes.Add(treeData.Employee.EmployeeName, treeData.Employee.LPN);
            BuildSuperSubTreeViews(resultingNode,treeData.SubEmployees);

            ExpandSelectedNode();

            //if (Session["selNode"] != null)
            //{
                
            //    List<TreeViewNode> ParentList = (List<TreeViewNode>)Session["ParentList"];
            //    foreach (var item in ParentList)
            //    {
            //        TreeViewNode tn = (TreeViewNode)(ParentList[ParentList.Count - ParentList.IndexOf(item) - 1]);
            //        subOrdinatesTreeView.Nodes.FindByName(tn.Name).Expanded = true;
            //    }

            //    TreeViewNode node = (TreeViewNode)Session["selNode"];
            //    node = subOrdinatesTreeView.Nodes.FindByName(node.Name);
            //    subOrdinatesTreeView.ExpandToNode(node);                
            //    subOrdinatesTreeView.SelectedNode = node;
            //}

        }
        private void BuildSuperSubTreeViews(TreeViewNode resultingNode,List<EmployeeTree> treeSubEmployees)
        {
            if (treeSubEmployees != null && treeSubEmployees.Count > 0)
            {
                foreach (EmployeeTree treeMember in treeSubEmployees)
                {
                    resultingNode.Nodes.Add(treeMember.Employee.EmployeeName, treeMember.Employee.LPN);
                }

                foreach (TreeViewNode childNode in resultingNode.Nodes)
                {
                    BuildSuperSubTreeViews(childNode, treeSubEmployees.First(x => x.Employee.LPN == childNode.Name).SubEmployees);
                }
            }
        }

        protected void ASPxMenu2_ItemClick(object source, DevExpress.Web.ASPxMenu.MenuItemEventArgs e)
        {
            
                switch (e.Item.Index)
                {
                    case 0:
                        Response.Redirect("DashBoardReport.aspx");
                        break;
                    case 1:
                        Response.Redirect("EmployeeDetails.aspx");
                        break;
                    case 2:
                        Response.Redirect("RedirectInfo.aspx?page=shift");

                        //  Response.Write("<script type='text/javascript'>window.open('" + ConfigMgr.Instance.GetValue(ConfigKeys.CNFG_SHIFT_SDTOOL) + "','_blank');</script>");
                        //Response.Redirect(ConfigMgr.Instance.GetValue(ConfigKeys.CNFG_SHIFT_SDTOOL));
                        break;
                    case 3:
                        Response.Redirect("AttendanceCalendar.aspx");

                        break;
                    case 4:
                        Response.Redirect("RedirectInfo.aspx?page=leave");
                        // Response.Write("<script type='text/javascript'>window.open('" + ConfigMgr.Instance.GetValue(ConfigKeys.CNFG_LEAVE_LMS) + "','_blank');</script>");
                        //Response.Redirect(ConfigMgr.Instance.GetValue(ConfigKeys.CNFG_LEAVE_LMS));
                        //Response.Redirect("LeaveCalendar.aspx");
                        break;
                    case 5:
                        Response.Redirect("WhereIsHe.aspx");
                        break;
                    case 6:
                        Response.Redirect("WhoIsIn.aspx");
                        break;
                    case 7:
                        Response.Redirect("Analytics.aspx");
                        break;
                    case 8:
                        Response.Redirect("Behaviours.aspx");
                        break;
                    case 9:
                        Response.Redirect("Reports.aspx");
                        break;
                    case 10:
                        string lpnToSwitch = string.Empty;

                        if (!IsQueenPersonated)
                        {
                            lpnToSwitch = ConfigMgr.Instance.GetValue(ConfigKeys.CNFG_QUEEN_ROLE_USER);
                            IsQueenPersonated = true;
                        }
                        else
                        {
                            lpnToSwitch = OriginalCurrentEmployee.LPN;
                            IsQueenPersonated = false;
                        }
                        Employee userToSwitchedTo = EmployeeManagerContext.GetEmployee(lpnToSwitch);
                        EmployeeTree treeToSwitchTo = EmployeeManagerContext.GetEmployeeTreeData(userToSwitchedTo);
                        CurrentEmployee = userToSwitchedTo;
                        SelectedEmployeeLPN = userToSwitchedTo.LPN;
                        EmployeeTreeData = treeToSwitchTo;
                        Session["selNode"] = null;
                        Response.Redirect("EmployeeDetails.aspx");
                        break;
                    case 12:
                        Response.Redirect("TempCardDetailsSaving.aspx");
                        break;
                    case 11:
                        try
                        {
                            Process proc = new Process();
                            ProcessStartInfo psi = new ProcessStartInfo();
                            psi.FileName = ConfigMgr.Instance.GetValue(ConfigKeys.CNFG_DATA_PULL_EXE_PATH);
                            psi.UseShellExecute = true;
                            proc.StartInfo = psi;
                            proc.Start();
                            //proc.WaitForExit();
                        }
                        catch (Exception ex)
                        {
                        }
                        finally
                        {
                            Response.Redirect("EmployeeDetails.aspx");
                        }
                        break;

                    default:
                        break;
                }
           
        }

        protected void subOrdinatesTreeView_NodeClick(object source, DevExpress.Web.ASPxTreeView.TreeViewNodeEventArgs e)
        {
            SelectedEmployeeLPN = subOrdinatesTreeView.SelectedNode.Name;
            OnTreeViewNodeSelected(EventArgs.Empty);
            TreeViewNode selNode = subOrdinatesTreeView.SelectedNode;
            Session["selNode"] = selNode;
            List<TreeViewNode> ParentList = new List<TreeViewNode>();
            while (selNode.Parent.Name != "")
            {
                selNode = selNode.Parent;
                ParentList.Add(selNode);

            }
            Session["ParentList"] = ParentList;
           // txtSearchName.Text = string.Empty;
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                Session["Searched"] = "1";
                if (Convert.ToString(cmbUser.Value) == "")
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please enter an Employee Name/LPN..!');", true);
                    return;
                }

                //TreeViewNode selNode = subOrdinatesTreeView.Nodes.FindByText(txtSearchName.Text);
                TreeViewNode selNode = subOrdinatesTreeView.Nodes.FindByName(cmbUser.Value.ToString());

                if (null != selNode)
                {

                    SelectedEmployeeLPN = selNode.Name;

                    //TreeViewNode selNode = subOrdinatesTreeView.Nodes.FindByName(SelectedEmployeeLPN);


                    Session["selNode"] = selNode;

                    List<TreeViewNode> ParentList = new List<TreeViewNode>();
                    while (selNode.Parent.Name != "")
                    {
                        selNode = selNode.Parent;
                        ParentList.Add(selNode);

                    }
                    Session["ParentList"] = ParentList;
                    // OnSearchClick(EventArgs.Empty);
                    OnTreeViewNodeSelected(EventArgs.Empty);
                    // FillSubOrdinatesTreeView();
                    ExpandSelectedNode();
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Page : Main.master.cs, Event : btnSearch_Click", ex);
                ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('An internal error occured. Reload the tool and try again. If issue still persists, please report to your administrator..!');", true);
            }
        }

        protected void OnSearchClick(EventArgs eventArgs)
        {
            if (this.ClickEventHandler != null)
            {
                this.ClickEventHandler(this, null);
            }
        }

        protected void OnTreeViewNodeSelected(EventArgs eventArgs)
        {
            if (this.MasterTreeViewNodeSelected != null)
            {
                this.MasterTreeViewNodeSelected(this, null);
            }
        }

        public void RestoreTreeSelection()
        {
            if (SelectedNode == null)
            {
                subOrdinatesTreeView.SelectedNode = subOrdinatesTreeView.Nodes.Where(x => x.Name == CurrentEmployee.LPN).FirstOrDefault ();
            }
            else
            {
                subOrdinatesTreeView.SelectedNode = SelectedNode;
            }
        }
        
        public void SetAllowCheckingInTreeview()
        {
            subOrdinatesTreeView.AllowCheckNodes = true;
        }
        public List<Employee> GetAllSelectedEmployees()
        {
            List<Employee> emps = new List<Employee>();
            SelectNodeRecursive(subOrdinatesTreeView.RootNode,ref emps);
            return emps;
        }
        private void SelectNodeRecursive(TreeViewNode treeNode, ref List<Employee> emps)
        {
            if (treeNode.Checked == true)
            {
                emps.Add(EmployeeManagerContext.GetEmployee(treeNode.Name));
            }
            foreach (TreeViewNode tn in treeNode.Nodes)
            {
                SelectNodeRecursive(tn,ref emps);
            }
        }
        public void EnableGroupedChecking()
        {
            subOrdinatesTreeView.CheckNodesRecursive = true;
        }
        public void DisableGroupedChecking()
        {
            subOrdinatesTreeView.CheckNodesRecursive = false;
        }

        internal void ExpandTreeToEmployee(Employee emp)
        {
            TreeViewNode node = subOrdinatesTreeView.Nodes.FirstOrDefault(x => x.Name == emp.LPN);
            subOrdinatesTreeView.ExpandToNode(node);
        }

     
    }
}